//
//  StatusListViewModel.swift
//  sinaWeiBo
//
//  Created by smartlei on 15/10/19.
//  Copyright © 2015年 smartlei. All rights reserved.
//

import Foundation
import SDWebImage

class StatusListViewModel {
    
    lazy var statusListViewModel = [StatusViewModel]()
    
    //加载数据
     func loadData(finished:(isSuccessed: Bool) -> ()) {
        
        NetworkTools.sharedTools.loadStatus { (result, error) -> () in
            //1 看是否出错
            if error != nil {
                print(" NetworkTools.sharedTools.laodStatus出错")
                return
            }
            
            //2 看数据能否转化成字典数组
            guard let array = result?["statuses"] as? [[String: AnyObject]] else {
                print(" result转化成数组出错")
                return
            }
           // print(array)
            //3 遍历字典字典转模型
            //3.1 创建可变数组
            var dataList = [StatusViewModel]()
            //3.2 遍历数组，字典转模型
            for dict in array {
//                print("--------")
//                print(dict["retweeted_status"])
                
                let model = StatusViewModel(status: Status(dict: dict))
                       
                dataList.append(model)
            }
   
            //3.3 保存模型数组：新来的加到数组的前边
            self.statusListViewModel = dataList + self.statusListViewModel
            
            //4 准备好数据回调
            //finished(isSuccessed: true)
            
            //5 对配图缓存
            self.imageCache(dataList, finished: finished)
   
        }
    }
    
    //缓存单张配图，用于计算宽高
    private func imageCache(listViewModel: [StatusViewModel],finished:(isSuccessed: Bool) -> ()){
        
        //1 创建调度组:注意放在外边
        let  group = dispatch_group_create()
        
        for statusViewModel in listViewModel {
            
            if statusViewModel.pic_urlsURL?.count != 1 {
                
                //继续重新循环
               continue
            }
        
            //入组监听block执行情况
            dispatch_group_enter(group)
            //配图只有一张照片 开始进行缓存
            // SDWebImage 的核心下载函数，如果本地缓存已经存在，同样会通过完成回调返回
            SDWebImageManager.sharedManager().downloadImageWithURL(statusViewModel.pic_urlsURL?.first,
                options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached],
                progress: nil,
                completed: { (image, _, _, _, _) -> Void in
                    
                    
                    //print(statusViewModel.pic_urlsURL?.first)
                  //离开调度组
                dispatch_group_leave(group)
            })
            
            
        }
        
        // 查看调度组任务是否完成:任务完成执行block
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finished(isSuccessed: true)
        }
        
        
    }
}
